package org.example.interfaces.filter;


import io.jsonwebtoken.Claims;
import org.example.config.IgnoreWhiteProperties;
import org.example.domain.model.factory.LoginTypeStrategeFactory;
import org.example.domain.model.repository.LoginTypeStrategeRepository;
import org.example.domain.system.constant.SecurityConstant;
import org.example.utils.JwtUtils;
import org.example.utils.ServletUtils;
import org.example.utils.StringUtils;
import org.example.web.result.BaseErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 鉴权
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    private static final Logger logger = LoggerFactory.getLogger(AuthFilter.class);

    // 排除过滤的 uri 地址，nacos自行添加
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;
    @Autowired
    private LoginTypeStrategeFactory loginTypeStrategeFactory;


    @Override
    public int getOrder() {
        return -10;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        String url = request.getURI().getPath();
        // 跳过不需要验证的路径
        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }
        String token = JwtUtils.getToken(request);
        if (StringUtils.isEmpty(token)) {
            return unauthorizedResponse(exchange, BaseErrorCode.IDEMPOTENT_TOKEN_NULL_ERROR.message());
        }
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null) {
            return unauthorizedResponse(exchange, BaseErrorCode.IDEMPOTENT_TOKEN_VERIFY_ERROR.message());
        }
        String userName = JwtUtils.getUserName(claims);
        if (StringUtils.isEmpty(userName)){
            return unauthorizedResponse(exchange, BaseErrorCode.IDEMPOTENT_TOKEN_VERIFY_ERROR.message());
        }
        String userTokenKey = JwtUtils.getTokenKey(claims);
        String loginType = JwtUtils.getLoginType(claims);
        String userId = JwtUtils.getUserId(claims);
        LoginTypeStrategeRepository loginTypeStrategeRepository = loginTypeStrategeFactory.getLoginTypeStrategeRepository(loginType);
        if (!loginTypeStrategeRepository.hasToken(userTokenKey)){
            return unauthorizedResponse(exchange, BaseErrorCode.IDEMPOTENT_TOKEN_LOGIN_STATUS_EXPIRED.message());
        }
        // 设置用户信息到请求
        addHeader(mutate, SecurityConstant.SECURITY_TOKEN_KEY, userTokenKey);
        addHeader(mutate, SecurityConstant.SECURITY_USER_ID, userId);
        addHeader(mutate, SecurityConstant.SECURITY_USER_NAME, userName);
        // 内部请求来源参数清除
        removeHeader(mutate, SecurityConstant.FROM_SOURCE);


        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }


    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String message){
        logger.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return ServletUtils.webFluxResponseWriter(exchange.getResponse(), message, HttpStatus.UNAUTHORIZED.value());
    }

    /**
     *  设置用户信息到请求
     */
    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value)
    {
        if (value == null)
        {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    /**
     * 内部请求来源参数清除
     * @param mutate
     * @param name
     */
    private void removeHeader(ServerHttpRequest.Builder mutate, String name)
    {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }


}
